/*
 *  Copyright (C) 2009 takaji
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
 * AccountPeriodView.java
 *
 * Created on Dec 27, 2009, 4:00:14 PM
 */
package dakside.hacc.modules.accounting.periodman;

import org.dakside.exceptions.ArgumentException;
import dakside.hacc.core.models.AccountPeriod;
import org.dakside.duck.helpers.SwingHelper;
import org.dakside.utils.Localizable;
import org.dakside.utils.ResourceCentre;
import java.awt.Component;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.dakside.duck.plugins.AppConstants;
import org.dakside.duck.plugins.Command;
import org.dakside.duck.plugins.DefaultCommandInvoker;
import org.dakside.duck.plugins.ToolbarContainer;

/**
 *
 * @author Takaji
 */
public class AccountPeriodView extends javax.swing.JPanel
        implements ToolbarContainer, Localizable {

    private static final Logger logger = Logger.getLogger(AccountPeriodView.class.getName());
    private ResourceCentre rc = ResourceCentre.getInstance(this);
    AccountPeriodController controller = null;

    /** Creates new form AccountPeriodView */
    public AccountPeriodView() {
        initComponents();
        localize();
        accountPeriodTable1.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

            public void valueChanged(ListSelectionEvent e) {

                AccountPeriod ap = accountPeriodTable1.getSelectedAccountPeriod();
                if (ap != null) {
                    accountPeriodDetails1.setAccountPeriod(ap);
                }
                refreshCloseButton();
            }
        });
        controller = new AccountPeriodController(this);

        //load account periods from DB
        loadAccountPeriodList();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        customToolbar = new javax.swing.JToolBar();
        btnClose = new javax.swing.JButton();
        accountPeriodDetails1 = new dakside.hacc.modules.accounting.periodman.AccountPeriodDetails();
        jScrollPane1 = new javax.swing.JScrollPane();
        accountPeriodTable1 = new dakside.hacc.modules.accounting.periodman.AccountPeriodTable();

        customToolbar.setFloatable(false);
        customToolbar.setRollover(true);
        customToolbar.setName("customToolbar"); // NOI18N

        btnClose.setText("btnClose");
        btnClose.setFocusable(false);
        btnClose.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnClose.setName("btnClose"); // NOI18N
        btnClose.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCloseActionPerformed(evt);
            }
        });
        customToolbar.add(btnClose);

        accountPeriodDetails1.setName("accountPeriodDetails1"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        accountPeriodTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        accountPeriodTable1.setName("accountPeriodTable1"); // NOI18N
        jScrollPane1.setViewportView(accountPeriodTable1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 402, Short.MAX_VALUE)
                    .addComponent(accountPeriodDetails1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 402, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(accountPeriodDetails1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 128, Short.MAX_VALUE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btnCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCloseActionPerformed
        //close a period
        closeAccountPeriod();
    }//GEN-LAST:event_btnCloseActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private dakside.hacc.modules.accounting.periodman.AccountPeriodDetails accountPeriodDetails1;
    private dakside.hacc.modules.accounting.periodman.AccountPeriodTable accountPeriodTable1;
    private javax.swing.JButton btnClose;
    private javax.swing.JToolBar customToolbar;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables

    private final void refreshCloseButton() {
        AccountPeriod[] aps = accountPeriodTable1.getSelectedAccountPeriods();

        if (aps != null && aps.length == 1 && aps[0] != null && aps[0].isPassed()) {
            btnClose.setEnabled(true);
            if (aps[0].getStatus() == AccountPeriod.CLOSED) {
                btnClose.setText(rc.getString("btnClose_open"));
            } else {
                btnClose.setText(rc.getString("btnClose"));
            }
        } else {
            btnClose.setEnabled(false);
        }
    }

    public void loadAccountPeriodList() {
        AccountPeriod[] aplist = controller.getAllAccountPeriods();
        ((AccountPeriodTable) accountPeriodTable1).reload(aplist);
    }

    private void closeAccountPeriod() {
        AccountPeriod ap = accountPeriodDetails1.getAccountPeriod();
        AccountPeriod selectedPeriod = accountPeriodTable1.getSelectedAccountPeriod();

        /*
         * Only can close not-null, opening and passed account period
         */
        if (ap != null && ap == selectedPeriod
                && ap.isPassed()) {
            if (ap.getStatus() == AccountPeriod.OPENING) {
                //close
                try {
                    ap.setStatus(AccountPeriod.CLOSED);
                    controller.save(ap);
                    //update table
                    int rowIndex = accountPeriodTable1.getSelectedRow();
                    accountPeriodTable1.repaint();
                } catch (ArgumentException ex) {
                    logger.log(Level.SEVERE, null, ex);
                }
            } else {
                //re-open
                try {
                    ap.setStatus(AccountPeriod.OPENING);
                    controller.save(ap);
                    //update table
                    int rowIndex = accountPeriodTable1.getSelectedRow();
                    accountPeriodTable1.repaint();
                } catch (ArgumentException ex) {
                    logger.log(Level.SEVERE, null, ex);
                }
            }

        } else {
            SwingHelper.alert(rc.getString("cannot_close"), rc.getString("cannot_close_header"));
        }
        refreshCloseButton();
    }

    private void saveAccountPeriod() {
        AccountPeriod ap = accountPeriodDetails1.getAccountPeriod();
        if (ap == null) {
            //XXX cannot save
            return;
        }

        //update or insert?
        AccountPeriod selectedPeriod = accountPeriodTable1.getSelectedAccountPeriod();
        if (ap == selectedPeriod) {
            //no need to create new line
            int rowIndex = accountPeriodTable1.getSelectedRow();
            accountPeriodTable1.repaint();
        } else {
            //clone current data & insert into table
            ap = ap.clone();
            accountPeriodTable1.add(ap);
            //create new account period
            accountPeriodDetails1.createNew();
        }
        controller.save(ap);
    }

    private void deleteSelectedAccountPeriods() {
        try {
            AccountPeriod[] selectedPeriods = accountPeriodTable1.getSelectedAccountPeriods();
            for (AccountPeriod selectedPeriod : selectedPeriods) {
                if (!controller.delete(selectedPeriod)) {
                    SwingHelper.alert(rc.getString("cannot_delete"),
                            rc.getString("cannot_delete_header"));
                    return;
                }
            }
            accountPeriodTable1.deleteSelectedRow();
        } catch (Exception ex) {
            logger.log(Level.WARNING, "Cannot delete account periods", ex);
        }

    }

    public void insertPeriod() {
        accountPeriodDetails1.createNew();
    }

    // <editor-fold defaultstate="collapsed" desc="TOOLBAR CONTAINER SUPPORT">
    private Component[] toolbar;

    public Component[] getToolbarItems() {
        if (toolbar == null) {
            toolbar = customToolbar.getComponents();
        }
        return toolbar;
    }
    private DefaultCommandInvoker myInvoker = null;

    public final synchronized DefaultCommandInvoker getInvoker() {
        if (myInvoker == null) {
            myInvoker = new DefaultCommandInvoker();
        }

        myInvoker.add(AppConstants.Commands.SAVE, new Command() {

            public Object invoke(Object[] args) {
                saveAccountPeriod();
                return true;
            }
        });
        myInvoker.add(AppConstants.Commands.REFRESH, new Command() {

            public Object invoke(Object[] args) {
                loadAccountPeriodList();
                return true;
            }
        });

        myInvoker.add(AppConstants.Commands.DELETE, new Command() {

            public Object invoke(Object[] args) {
                deleteSelectedAccountPeriods();
                return true;
            }
        });
        myInvoker.add(AppConstants.Commands.NEW, new Command() {

            public Object invoke(Object[] args) {
                insertPeriod();
                return true;
            }
        });

        return myInvoker;
    }
    //END OF TOOLBAR CONTAINER SUPPORT
//</editor-fold>

    public void localize() {
        rc = ResourceCentre.getInstance(this);
        btnClose.setText(rc.getString("btnClose"));
    }
}
